package com.jztd.platfrom.base.config;

import com.google.common.collect.Lists;
import com.jztd.platfrom.base.interceptor.UnifiedResponseInterceptor;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.Collections;
import java.util.List;

/**
 * 请求结果统一包装配置
 *
 * @author lj
 * @date 2025/08/03
 */
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UnifiedResponseConfigurer {
    private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Bean
    public UnifiedResponseInterceptor unifiedResponseInterceptor() {
        List<HandlerMethodReturnValueHandler> handlers = requestMappingHandlerAdapter.getReturnValueHandlers();
        RequestResponseBodyMethodProcessor processor = CollectionUtils.isEmpty(handlers) ? null :
                handlers.stream().filter(handler -> handler instanceof RequestResponseBodyMethodProcessor)
                        .map(handler -> (RequestResponseBodyMethodProcessor) handler).findAny().orElse(null);
        return new UnifiedResponseInterceptor(processor);
    }

    @PostConstruct
    public void register() {
        List<HandlerMethodReturnValueHandler> handlers2 = requestMappingHandlerAdapter.getReturnValueHandlers();
        RequestResponseBodyMethodProcessor processor = CollectionUtils.isEmpty(handlers2) ? null :
                handlers2.stream().filter(handler -> handler instanceof RequestResponseBodyMethodProcessor)
                        .map(handler -> (RequestResponseBodyMethodProcessor) handler).findAny().orElse(null);
        UnifiedResponseInterceptor unifiedResponseInterceptor = new UnifiedResponseInterceptor(processor);
        List<HandlerMethodReturnValueHandler> handlers = this.requestMappingHandlerAdapter.getReturnValueHandlers();
        if (CollectionUtils.isEmpty(handlers)) {
            this.requestMappingHandlerAdapter.setReturnValueHandlers(Collections.singletonList(unifiedResponseInterceptor));
            return;
        }
        List<HandlerMethodReturnValueHandler> replaceHandlers = Lists.newArrayListWithExpectedSize(handlers.size() + 1);
        replaceHandlers.add(unifiedResponseInterceptor);
        replaceHandlers.addAll(handlers);
        this.requestMappingHandlerAdapter.setReturnValueHandlers(replaceHandlers);
    }
}
